package com.lanswon.qzsmk.util.pdfutil;   
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.LoggerFactory;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;  
import com.itextpdf.text.pdf.BaseFont;  
import com.itextpdf.text.pdf.PdfReader;  
import com.itextpdf.text.pdf.PdfStamper;
import com.lanswon.qzsmk.exception.SystemException;

import ch.qos.logback.classic.Logger;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;  
   
/**
 * 描述：PDF文件类
 * 创建日期：2018/01/26
 * 版本：v1.0
 * @author 惠国磊 
 *
 */
public class PDFTempletTicket {  
	     
	     /*1.模板文件的路径*/
         private String templatePdfPath;  
         private String ttcPath;
         /*3.目标文件的路径*/
         private String targetPdfpath;  
         private Ticket ticket; 
         private StorageTicket storageTicket;
         private final static Logger logger = (Logger) LoggerFactory.getLogger(PDFTempletTicket.class); 
          
         public PDFTempletTicket() {  
            super();  
         }  
          
         public PDFTempletTicket(String templatePdfPath, String ttcPath,  
                            String targetPdfpath, Ticket ticket,StorageTicket storageTicket) {  
            this.templatePdfPath= templatePdfPath;  
            this.ttcPath= ttcPath;  
            this.targetPdfpath= targetPdfpath;  
            this.ticket= ticket;  
            this.storageTicket= storageTicket;
         }  
          
         public void templetStorageTicket(File file){
        	 logger.info("templetStorageTicket########start");
        	 PdfReader reader;
			try {
				reader = new PdfReader(templatePdfPath);
			} catch (IOException e1) {
				e1.printStackTrace();
				String msg="系统创建PDF异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);
				
			}  
             ByteArrayOutputStream bos = new ByteArrayOutputStream();  
             PdfStamper ps;
			try {
				ps = new PdfStamper(reader, bos);
			} catch (DocumentException e1) {
				e1.printStackTrace();
				String msg="系统创建PDF模板异常";
				logger.error(msg);
				throw new SystemException(SystemException.DocumentException, msg);
			} catch (IOException e) {
				e.printStackTrace();
				String msg="系统创建PDF模板异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);
			} 
			
             
             /*使用中文字体 */  
             BaseFont bf = null;
			try {
				bf = BaseFont.createFont(PDFTempletTicket.class.getResource("/") +
						       "simsun.ttc,1",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			} catch (DocumentException e1) {
				e1.printStackTrace();
				String msg="系统创建字体异常";
				logger.error(msg);
				throw new SystemException(SystemException.DocumentException, msg);

			} catch (IOException e) {
				e.printStackTrace();
				String msg="系统创建字体异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);

			} 
			
       
             ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();   
             fontList.add(bf);   
                         
             AcroFields af = ps.getAcroFields();  
             af.setSubstitutionFonts(fontList); 
             
             //设置变量域
             try {
				af.setField("title", storageTicket.getTitle());
			
             af.setField("amount", String.valueOf(storageTicket.getAmount()));
             af.setField("branchNo", storageTicket.getBranchNo());
             af.setField("incomingDate", storageTicket.getOperateDate());
             af.setField("storageNo", storageTicket.getStorageNo());
             
             //pdf设置
             List<String> cardPNameList = storageTicket.getCardPNameList();             
             List<String> makeCardNoList = storageTicket.getMakeCardNoList();
             List<Integer> amountList = storageTicket.getSubAmountList();
             List<String> companyList = storageTicket.getCompanyList();
             
             //按制卡批号进行分组显示
             if(makeCardNoList!=null&&makeCardNoList.size()>0){
            	 for(int j=0;j<makeCardNoList.size();j++){
                	 af.setField("makeCardNo_"+(j+1), makeCardNoList.get(j));
                	 af.setField("cardPName_"+(j+1), cardPNameList.get(j));
                	 af.setField("subAmount_"+(j+1), String.valueOf(amountList.get(j)));
                	 if(companyList!=null){
                		 af.setField("company_"+(j+1), companyList.get(j));
                	 }
                 }
             //如果制卡批号为空，表示由网点向中心库配送，按卡名称进行分组
             }else{
            	 if(cardPNameList!=null&&cardPNameList.size()>0){
            		 for(int j=0;j<cardPNameList.size();j++){
                   // 	 af.setField("makeCardNo_"+(j+1), makeCardNoList.get(j));
                    	 af.setField("cardPName_"+(j+1), cardPNameList.get(j));
                    	 af.setField("subAmount_"+(j+1), String.valueOf(amountList.get(j)));
                     }
            	 }
             }
             
             } catch (IOException e) {
            	 e.printStackTrace();
            	 String msg="PDF设置字段异常";
     			logger.error(msg);
     			throw new SystemException(SystemException.IOException, msg);
     			
     		} catch (DocumentException e) {
     			e.printStackTrace();
     			String msg="PDF设置字段异常";
     			logger.error(msg);
     			throw new SystemException(SystemException.DocumentException, msg);
     			
     		}
 			
             
             ps.setFormFlattening(true);  
             try {
				ps.close();
			} catch (DocumentException e) {
				e.printStackTrace();
				String msg1="IO流关闭异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

			} catch (IOException e) {
				e.printStackTrace();
				String msg1="IO流关闭异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

			}  
                    
             FileOutputStream fos;
			try {
				fos = new FileOutputStream(file);
				fos.write(bos.toByteArray());
	             fos.flush();
	             fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				 String msg1="系统找不到文件异常";
					logger.error(msg1);
					throw new SystemException(SystemException.FileNotFoundException, msg1);

			}  catch (IOException e) {
				e.printStackTrace();
				String msg1="IO流关闭异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

			}  

        	 logger.info("templetStorageTicket########end");
         }
         
         
         public void templetTicket(File file) {  
                    
             PdfReader reader;
			try {
				reader = new PdfReader(templatePdfPath);
			} catch (IOException e) {
				e.printStackTrace();
				String msg="系统创建PDF异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);
				
			}  
             ByteArrayOutputStream bos = new ByteArrayOutputStream();  
             PdfStamper ps;
			try {
				ps = new PdfStamper(reader, bos);
			} catch (DocumentException e) {
				e.printStackTrace();
				String msg="系统创建PDF模板异常";
				logger.error(msg);
				throw new SystemException(SystemException.DocumentException, msg);
			} catch (IOException e) {
				e.printStackTrace();
				String msg="系统创建PDF模板异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);
			} 
                    
             /*使用中文字体 */  
             BaseFont bf = null;
			try {
				bf = BaseFont.createFont(PDFTempletTicket.class.getResource("/") +
						       "simsun.ttc,1",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			} catch (DocumentException e) {
				e.printStackTrace();
				String msg="系统创建字体异常";
				logger.error(msg);
				throw new SystemException(SystemException.DocumentException, msg);

			} catch (IOException e) {
				e.printStackTrace();
				String msg="系统创建字体异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);

			} 
       
             ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();   
             fontList.add(bf);   
             
             // 注意：根据文件的名称设定不同的文本域
             // 1.解析文件名
             int beginIndex = templatePdfPath.lastIndexOf("/")+1;
             String fileName = templatePdfPath.substring(beginIndex);
             if(logger.isDebugEnabled()){
            	 logger.debug("模板文件路径====>"+templatePdfPath);
            	 logger.debug("模板文件名称====>"+fileName);
             }             
             AcroFields af = ps.getAcroFields();  
             af.setSubstitutionFonts(fontList); 
             
             //logger出所有的ticket变量
             if(logger.isDebugEnabled()){
            	 logger.debug(""+ticket.getCert_no());
            	 logger.debug(""+ticket.getBussiness_type());
            	 logger.debug(""+ticket.getCard_type());
            	 logger.debug(""+ticket.getCard_no());
            	 logger.debug(""+ticket.getOld_card_no());
            	 logger.debug(""+ticket.getOld_card_balance());
            	 logger.debug(""+ticket.getNew_card_no());
            	 logger.debug(""+ticket.getNew_card_balance());
            	 logger.debug(""+ticket.getCurrent_balance());
            	 logger.debug(""+ticket.getReChargeMoney());
            	 logger.debug(""+ticket.getAfterRecharge());
            	 logger.debug(""+ticket.getCardDeposit());
            	 logger.debug(""+ticket.getLogoffTotalMoney());
            	 logger.debug(""+ticket.getCardLogoffMoneyApoointment());
            	 logger.debug(""+ticket.getCardAppointment());
            	 logger.debug(""+ticket.getBranchNo());
            	 logger.debug(""+ticket.getOperatorNo());
            	 logger.debug(""+ticket.getOperateDate());
            	 logger.debug(""+ticket.getOperateTime());
             }
             
             // 2.设定通用的文本域
             // 2.1 凭证号
             try {
				af.setField("credentialNo",ticket.getCert_no());
			
             // 2.2 业务类型
             af.setField("bussinessType", ticket.getBussiness_type());
             // 2.3 卡类型
             af.setField("cardType",ticket.getCard_type());  
             // 2.4 网点号
             af.setField("branchNo",ticket.getBranchNo()); 
             // 2.5 操作员号
             af.setField("operatorNo",ticket.getOperatorNo());  
             // 2.6 办理时间
             af.setField("operateDate",ticket.getOperateDate());
             // 2.7 申请登记，换卡登记，补卡登记凭证的文本域
             if("CREDENTIAL_TEMP1.pdf".equals(fileName)){
            	 //2.7.1 市民卡号
            	 af.setField("cardNo",ticket.getCard_no());
            	 //2.7.2 预约卡日期
                 af.setField("cardAppointment",ticket.getCardAppointment());
                 //2.7.3 预约卡日期
                 af.setField("cardpName",ticket.getCardpName()); 
             // 2.8 退卡登记凭证的文本域
             }else if("CREDENTIAL_TEMP2.pdf".equals(fileName)){
            	 //2.8.1 市民卡号
            	 af.setField("cardNo",ticket.getCard_no());
            	 //2.8.2 预约退卡日期
                 af.setField("cardLogoffMoneyApoointment",ticket.getCardLogoffMoneyApoointment());
                 //2.8.3 工本费
                 af.setField("cardDeposit",ticket.getCardDeposit());
                 // 2.9 换卡现场发卡，换卡发卡，补卡现场发卡，补卡发卡 凭证的文本域
             }else if("CREDENTIAL_TEMP3.pdf".equals(fileName)){
            	 //2.9.1 旧卡卡号
            	 af.setField("oldCardNo",ticket.getOld_card_no());
            	 //2.9.2 旧卡余额
                 af.setField("oldCardBalance",ticket.getOld_card_balance());
                 //2.9.3 新卡卡号
                 af.setField("newCardNo",ticket.getNew_card_no());
                 //2.9.4 新卡余额
                 af.setField("newCardBalance",ticket.getNew_card_balance());
                 //2.8.5 工本费
                 af.setField("cardDeposit",ticket.getCardDeposit());
             // 2.10 申请现场发卡，申请发卡，现场售卡，正式挂失，挂失解挂的文本域
             }else if("CREDENTIAL_TEMP4.pdf".equals(fileName)){
            	 //2.10.1 市民卡号
                 af.setField("cardNo",ticket.getCard_no());
             // 2.11 现场退卡退款凭证的文本域
             }else if("CREDENTIAL_TEMP5.pdf".equals(fileName)){
            	 //2.11.1  市民卡号
                 af.setField("cardNo",ticket.getCard_no());
                 //2.11.2 卡内余额
                 //af.setField("currentBalance",ticket.getCurrent_balance());
                 //2.11.3 卡押金
                 af.setField("cardDeposit",ticket.getCardDeposit());
                 //2.11.4 退款金额合计
                 af.setField("logoffTotalMoney",ticket.getLogoffTotalMoney());
             // 2.12 退卡退款凭证的文本域
             }else if("CREDENTIAL_TEMP6.pdf".equals(fileName)){
            	 //2.12.1  市民卡号
                 af.setField("cardNo",ticket.getCard_no());
                 //2.12.2 卡内余额
                 //af.setField("currentBalance",ticket.getCurrent_balance());
                 //2.12.3 卡押金
                 af.setField("cardDeposit",ticket.getCardDeposit());
                 //2.12.4 退款金额合计
                 af.setField("logoffTotalMoney",ticket.getLogoffTotalMoney());
                 //2.12.5 预约退款日期
                 af.setField("cardLogoffMoneyApoointment",ticket.getCardLogoffMoneyApoointment());
             // 2.13 电子钱包充值
             }else if("CREDENTIAL_TEMP7.pdf".equals(fileName)){
            	 //2.13.1  市民卡号
                 af.setField("cardNo",ticket.getCard_no());
                 //2.13.2 卡内余额
                 af.setField("currentBalance",ticket.getCurrent_balance());
                 //2.13.3 充值金额
                 af.setField("rechargeMoney",ticket.getReChargeMoney());
                 //2.13.4 充值后金额
                 af.setField("afterRecharge",ticket.getAfterRecharge());
                 //2.13.5 办理时间
                 af.setField("operateTime",ticket.getOperateTime());
             }else if("CREDENTIAL_TEMP8.pdf".equals(fileName)){
            	 //2.14.1 单位名称
                 af.setField("corpName",ticket.getCorpName());
                 //2.14.2 数量
                 af.setField("recordNum",ticket.getRecordNum());
                 //2.14.3 卡产品
                 af.setField("cardpName",ticket.getCardpName());
             }else if("CREDENTIAL_TEMP9.pdf".equals(fileName)){
            	 //2.15.1  工作单位
                 af.setField("corpName",ticket.getCorpName());
                 //2.15.2 卡产品
                 af.setField("cardpName",ticket.getCardpName());
                 //2.15.3 数量
                 af.setField("recordNum",ticket.getRecordNum());
                 //2.15.4 总金额
                 af.setField("cardDeposit",ticket.getCardDeposit());
             }
             } catch (IOException e) {
            	 e.printStackTrace();
            	 String msg="PDF设置字段异常";
     			logger.error(msg);
     			throw new SystemException(SystemException.IOException, msg);
     			
     		} catch (DocumentException e) {
     			e.printStackTrace();
     			String msg="PDF设置字段异常";
     			logger.error(msg);
     			throw new SystemException(SystemException.DocumentException, msg);
     			
     		}
                    
             ps.setFormFlattening(true);  
             try {
				ps.close();
			} catch (DocumentException e) {
				e.printStackTrace();
				String msg="PDF模板关闭异常";
				logger.error(msg);
				throw new SystemException(SystemException.DocumentException, msg);
			} catch (IOException e) {
				e.printStackTrace();
				String msg="PDF模板关闭异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);
			}
                    
             FileOutputStream fos;
			try {
				fos = new FileOutputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				String msg="系统找不到文件异常";
				logger.error(msg);
				throw new SystemException(SystemException.FileNotFoundException, msg);

			}  
			try {
				fos.write(bos.toByteArray());
				fos.flush();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
				String msg="IO流异常";
				logger.error(msg);
				throw new SystemException(SystemException.IOException, msg);

			}  
         }  
   
         /** 
          * @return the templatePdfPath 
          */  
         public String getTemplatePdfPath() {  
                   return templatePdfPath;  
         }  
   
         /** 
          * @param templatePdfPath the templatePdfPathto set 
          */  
         public void setTemplatePdfPath(String templatePdfPath) {  
                   this.templatePdfPath= templatePdfPath;  
                   System.out.println("templatePdfPath:"+templatePdfPath);
         }  
   
         /** 
          * @return the ttcPath 
          */  
         public String getTtcPath() {  
                   return ttcPath;  
         }  
   
         /** 
          * @param ttcPath the ttcPath to set 
          */  
         public void setTtcPath(String ttcPath) {  
                   this.ttcPath= ttcPath;  
         }  
   
         /** 
          * @return the targetPdfpath 
          */  
         public String getTargetPdfpath() {  
                   return targetPdfpath;  
         }  
   
         /** 
          * @param targetPdfpath the targetPdfpath toset 
          */  
         public void setTargetPdfpath(String targetPdfpath) {  
                   this.targetPdfpath= targetPdfpath;  
         }  
   
         /** 
          * @return the ticket 
          */  
         public Ticket getTicket() {  
                   return ticket;  
         }  
   
         /** 
          * @param ticket the ticket to set 
          */  
         public void setTicket(Ticket ticket) {  
                   this.ticket= ticket;  
         }

		public StorageTicket getStorageTicket() {
			return storageTicket;
		}

		public void setStorageTicket(StorageTicket storageTicket) {
			this.storageTicket = storageTicket;
		}  
          
          
}  

